package ro.isdc.navigator.utils.hibernate.usertypes;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;
/**
 * Converts an int to a SQL BIGLINT type and viceversa.
 * 
 * @author Andrei Chirila
 * @version 1.0
 * @date Jul 2, 2009
 */
public class BigIntegerType implements UserType {

  public int[] sqlTypes() {
    return new int[] { Types.BIGINT};
  }

  public Class<Long> returnedClass() {
    return long.class;
  }

  public boolean isMutable() {
    return false;
  }

  public Object deepCopy(final Object value) {
    return value;
  }

  public Serializable disassemble(Object value) {
    return (Serializable) value;
  }

  public Object assemble(final Serializable cached, final Object owner) {
    return cached;
  }

  public Object replace(final Object original, Object target, final Object owner) {
    return original;
  }

  public boolean equals(Object x, Object y) {
    if (x == y)
      return true;
    if (x == null || y == null)
      return false;
    return x.equals(y);
  }

  public int hashCode(final Object x) {
    return x.hashCode();
  }

  public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner)
      throws SQLException {
    Long value = (Long)Hibernate.LONG.nullSafeGet(resultSet, names[0]);
    if(value == null) {
      return (long)-1;
    }else {
      return value.longValue();
    }
  }

  public void nullSafeSet(PreparedStatement statement, Object value, int index)
      throws HibernateException, SQLException {
    if (value == null) {
      statement.setNull(index, Types.BIGINT);
    } else if(((Long)value).longValue() <= 0){
      statement.setNull(index, Types.BIGINT);
    }else{
      statement.setLong(index, ((Long)value).longValue());
    }
  }

}